package com.Filters.LogFilters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class LogURIFilter implements Filter {
	private ShowTime showTime;

	@Override
	public void destroy() {
		

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		long start = System.nanoTime();
		String file = ((HttpServletRequest) request).getRequestURI();
		try {

			chain.doFilter(request, response);
		} finally {
			System.out.println("Resource: " + file + " Time used: " + (System.nanoTime() - start) / showTime.getTimeUnits() + showTime.resultTime());
		}

	}

	@Override
	public void init(FilterConfig config) throws ServletException { 
		String timeFormat = config.getInitParameter("timeformat");

		if (timeFormat == null) {
			throw new ServletException("Init parameter 'timeformat' is absent in your web.xml!");
		}

		if ((ShowTime.valueOf(timeFormat) == ShowTime.NSEC) | (ShowTime.valueOf(timeFormat) == ShowTime.MSEC)) {
			showTime = ShowTime.valueOf(timeFormat);
		} else {

			throw new ServletException("Uncknow time format, provided: " + timeFormat + ", ecxpected: " + "timeformat");
		}

	}

}
